package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
//        判断是否为登录操作  如果是登录操作直接放行
        String path = request.getURI().getPath();  // api/v1/channel/list  /login/in
        if(path.contains("/login")){
            return chain.filter(exchange);  //直接放行
        }

        String token = request.getHeaders().getFirst("token");
        //        判断请求头中是否携带token 如果没有直接返回401
        if(StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
//        如果携带token判断token是否有效
        Claims claims = AppJwtUtil.getClaimsBody(token);
        if(claims!=null){
            //        如果有效从token中解析出userId和name放到请求头中继续进入到后面的微服务中
            int type = AppJwtUtil.verifyToken(claims);
//            -1：有效，0：有效
            if(type==-1||type==0){
                Integer userId = claims.get("userId", Integer.class);
                String name = claims.get("name", String.class);
                request.mutate().header("userId",userId.toString());
                request.mutate().header("name",name);
                return chain.filter(exchange);  //放行
            }
        }

        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
